﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MiserBlogMVC.Models;
using MiserBlogData.Entities;
using MiserBlogHelper.Helper;

namespace MiserBlogMVC.HTTP
{
    public class BaseHTTPHandler : IHttpHandler
    {
        protected string resultJSON = string.Empty;
        protected A_Person request_person = null;

        public virtual void ProcessRequest(HttpContext context)
        {
            if (AuthUser(context) && AuthVar(context) && Exec(context)) { }

            context.Response.Write(resultJSON);
        }

        protected virtual bool AuthUser(HttpContext context)
        {
            if (AuthUserEvent(context) == false)
            {
                resultJSON = new HTTPResult { ExecState = false, ExecContent = "帐号或密码错误"  }.ToString();
                return false;
            }

            return true;
        }
        protected virtual bool AuthUserEvent(HttpContext context)
        {
            UserVIPIdentity userVIPIdentity = new UserVIPIdentity();
            request_person = userVIPIdentity.Person;
            UserPrincipal userVIPPrincipal = new UserPrincipal(userVIPIdentity);
            return userVIPPrincipal.IsInRole(PersonRole.UserVIP.ToString());
        }

        protected virtual bool AuthVar(HttpContext context)
        {
            if (AuthVarEvent(context) == false)
            {
                resultJSON = new HTTPResult { ExecState = false, ExecContent = "请求参数错误" }.ToString();
                return false;
            }

            return true;
        }
        protected virtual bool AuthVarEvent(HttpContext context)
        {
            return false;
        }

        protected virtual bool Exec(HttpContext context)
        {
            bool state = false;
            try
            {
                state = ExecEvent(context);
            }
            catch
            {

            }
            if (state == false)
            {
                resultJSON = new HTTPResult { ExecState = false, ExecContent = "执行出错" }.ToString();
            }
            return state;
        }
        protected virtual bool ExecEvent(HttpContext context)
        {
            return false;
        }


        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }
    }
}